import utils from "../../../utils/utils";
import User from "../../../utils/user";
import { GoodsHttp } from '../../../api/goods.js'
import { HomeHttp } from '../../../api/home.js'
import { storeInfoMap, storeGoodsDetailsMap } from '../../../utils/dataMap.js'
import Data from "../../../utils/data";

const goodsModel = new GoodsHttp();
const homeModel = new HomeHttp();
const app = getApp()
const AD_UNIT_ID = 'adunit-b5fbbe96f27d0e64'
const SECKILL_STEPS = [
  { text: '1.观看1次广告' },
  { text: '2.邀请好友' },
  { text: '3.再看1次广告' }
]
Page({

  /**
   * 页面的初始数据
   */
  videoAd:null,
  data: {
    isNoPurchase: true, // 是否没有购买过
    seckillSteps: SECKILL_STEPS, // 秒杀步骤列表
    seckillStepsActive: 0, // 秒杀当前步骤
    inviteNum: 0, // 邀请人数
    seckillProgress: [], // 秒杀进度
    isShowAddress: false, // 是否显示地址
    addressInfo: {}, // 地址信息
    storeInfo: {}, // 店铺信息
    storeId: '', // 店铺Id
    goodsId: 0, // 商品Id
    goodsInfo: {}, // 商品信息
    goodsDetailsImgs: [], // 商品详情图
    goodsSwiper: [], // 商品轮播图
    currentSwiper: 1, // 当前轮播图 index
    countTime: 0, // 倒计时
    countTimeDate: {}, // 倒计时 item
    seckillStatus: 0, // 秒杀状态：1 热抢中， 2，开抢中 or 已结束 ，3未开抢
    startTimestamp: 0, // 秒杀开始时间
    endTimestamp: 0, // 秒杀结束时间
    previewImage: '', // 预览分享图片
    previewBoxHeight: '', // 预览分享图片容器高度
    previewHeight: '', // 预览分享图片高度
    isShowPreViewImage: false, // 是否显示分享图片预览弹窗
    viewAdNum: 0, // 观看广告次数
    windowWidth: 0, // 屏幕宽度

    mySeckillBean: 0, // 我的秒杀豆
    diffSeckillBean: 0, // 参加秒杀相差秒杀豆
    seckillTaskConfig: {}, // 秒杀任务配置
    isShowAlertDialog: false, // 是否显示提示弹出框
    isShowExchangeDialog: false, // 是否显示秒杀豆兑换弹出框
    isShowTaskPopup: false, // 是否显示弹出层
    isShowTabbarMore: false, // 是否显示更多操作
    isLike: false, // 是否收藏
    initUser: true,
    openLogin: false,
  },

  async initPage(options) {
    let systemInfo = wx.getSystemInfoSync();
    let self = this;
    this.setData({
      windowWidth: systemInfo.windowWidth,
      goodsId: options.id,
      seckillTaskConfig: app.globalData.pageConfig.seckillBean
    });
    /**
     * 获取配置信息
     */
    Data.getDictConfig('pageConfig',function (result) {
      self.setData({
        seckillTaskConfig: result.seckillBean
      });
    });
    if (app.globalData.userInfo && app.globalData.userInfo.uid) {
      await this.httpGetYddGoodsDetails(); // 获取商品信息
      await this.httpGetMySeckillBean(); // 获取我的秒杀豆
    } else {
      this.setData({
        initUser: false,
        openLogin: true
      })
    }
    setTimeout(function () {
      self.createVideoAd(); // 创建视频广告id
    },100);
    //动态计算弹出窗的高度
    let height = systemInfo.windowHeight;
    let rpxHeight = utils.rpxToPx(220);
    let padding = utils.rpxToPx(120);
    self.setData({
      previewBoxHeight:'height:' + (height - (rpxHeight + padding)) + 'px;',
      previewHeight:'height:' + (height - (rpxHeight + padding)) + 'px;',
    });
    if (options.hasOwnProperty('ekey')) {
      utils.UserUv(options.ekey);
      User.UvTrackPut(options.ekey);
    }
  },

  // 初始化分享图片弹窗相关高度
  initPreviewHeight () {
    let systemInfo = wx.getSystemInfoSync();
    let height = systemInfo.windowHeight;
    let rpxHeight = utils.rpxToPx(220);
    let padding = utils.rpxToPx(120);
    self.setData({
      previewBoxHeight:'height:' + (height - (rpxHeight + padding)) + 'px;',
      previewHeight:'height:' + (height - (rpxHeight + padding)) + 'px;',
    });
  },

  // swiper change事件
  onChangeSwiper: function (e) {
    this.setData({
      currentSwiper: e.detail.current + 1
    })
  },

  // 倒计时组件 - 时间改变触发
  onCountDownChange(e) {
    this.setData({
      countTimeDate: e.detail
    });
  },

  // 倒计时组件 - 当倒计时结束时触发
  onCountDownFinish() {
    if (this.data.seckillStatus !== 2) {
      this.httpGetYddGoodsDetails()
    }
  },

  // 选择地址
  selectAddress () {
    wx.navigateTo({
      url: `/pages/me/address/manage/manage`
    })
  },

  // 更新地址
  upAddress (address) {
    this.setData({
      isShowAddress: true,
      addressInfo: address
    })
  },

  // 参与秒杀
  onJoinSeckill() {
    const { seckillStepsActive, isShowAddress, goodsInfo, addressInfo, seckillStatus, isNoPurchase } = this.data
    if (seckillStatus === 2 || goodsInfo.stockNum <= 0 || !isNoPurchase) {
      return
    }
    switch (seckillStepsActive) {
      case 0: // 第一步 - 观看1次广告
        this.onViewAd()
        break
      case 1: // 第二步 - 邀请好友
        this.onShareGoods()
        break
      case 2: // 第三步 - 再看1次广告
        this.onViewAd()
        break
      case 3:
        if (seckillStatus !== 1) { // 判断活动是否开始
          utils.msg('活动未开始，暂不能购买！')
          return
        }
        // 判断是否选择地址，已选地址则【立即购买】，否则【选择地址】
        isShowAddress ? this.nowBuyGoods() : this.selectAddress()
        break
      default:
        break
    }
  },

  // 立即购买
  nowBuyGoods () {
    const { goodsInfo, addressInfo } = this.data
    homeModel.createSeckillOrder({
      goods_name: goodsInfo.goodsName,
      goods_img: goodsInfo.goodsThumbnailImg,
      spu_id: goodsInfo.goodsId,
      sku_id: goodsInfo.singleSku.goods_sku_id,
      price: goodsInfo.goodsMemberPrice,
      addr_id: addressInfo.addr_id,
      addrs_info: addressInfo.address
    }).then((res) => {
      utils.msg('订单创建成功！')
      wx.navigateTo({
        url: '/pages/order/seckillOrder/seckillOrder'
      })
      this.httpGetSeckillStepsInfo(); // 获取秒杀步骤信息
    })
  },

  // 弹出层 - 确认操作
  onAlertDialogConfirm() {
    this.createOrder()
  },

  // 创建订单
  createOrder() {
    const { goodsInfo, storeInfo, storeId } = this.data;
    let serviceCenterId = storeInfo.serviceCenterId;
    let joinSeckillNeedBean = goodsInfo.joinSeckillNeedBean;
    let orderData = [{
      sku_id: goodsInfo.singleSku.goods_sku_id,
      spu_id: goodsInfo.goodsId,
      amount: 1,
    }];
    wx.navigateTo({
      url: `/pages/goods/pendingOrder/pendingOrder?id=${JSON.stringify(orderData)}&storeId=${storeId}&serviceId=${serviceCenterId}&involvementPea=${joinSeckillNeedBean}`
    });
  },

  // ========================================================================================
  // 秒杀豆 - 任务

  // 任务 - 关闭任务赚秒杀豆弹窗层
  onCloseTaskPopup() {
    this.setData({
      isShowTaskPopup: false
    })
  },

  // 任务 - 兑换秒杀豆
  onExchange() {
    if(this.data.mySeckillBean) {
      this.setData({
        isShowExchangeDialog: true
      })
    }
  },

  // 任务 - 兑换秒杀豆 - 确认
  onExchangeDialogConfirm() {
    const { goodsInfo } = this.data
    homeModel.seckillBeanExchange({
      pea_count: this.data.mySeckillBean
    }).then((res) => {
      utils.msg('兑换成功！')
      let seckillBeanBlance = res.miao_blance
      let calculateDiff = seckillBeanBlance - goodsInfo.joinSeckillNeedBean
      this.setData({
        mySeckillBean: seckillBeanBlance,
        diffSeckillBean: calculateDiff >= 0 ? 0 : Math.abs(calculateDiff),
        isShowTaskPopup: false
      })
    })
  },
  // 分享秒杀商品
  onShareGoods () {
    let self = this;
    const { seckillStatus, goodsInfo } = this.data
    if (seckillStatus === 2 || goodsInfo.stockNum <= 0) {
      return
    }
    utils.request({
      url:'/yddgoods/SeckillGoodsPosterV2',
      data:{
        "spu_id": this.data.goodsId,
      },
      loading: true,
      handle: true,
      callback:function (res) {
        self.setData({
          isShowPreViewImage:true,
          previewImage:res.res.img_url,
        });
        // wx.previewImage({
        //   current: res.res.img_url, // 当前显示图片的http链接
        //   urls: [res.res.img_url] // 需要预览的图片http链接列表
        // })
      }
    });
  },

  // ========================================================================================

  // ========================================================================================
  // 底部tabbar：更多、收藏、分享、立即购买

  // tabbar - 更多
  onTabbarMore () {
    this.setData({
      isShowTabbarMore: !this.data.isShowTabbarMore
    })
  },

   // 页面点击 - 关闭tabbar更多
  onPageClick() {
    console.log('onPageClick')
    this.onCloseTabbarMore()
  },

  // tabbar - 关闭tabbar更多弹出
  onCloseTabbarMore () {
    if (this.data.isShowTabbarMore) {
      this.setData({
        isShowTabbarMore: false
      })
    }
  },

  // tabbar - 收藏
  onTabbarLove () {
    if (this.data.isLike) {
      this.httpCancelGoodsLike()
    } else {
      this.httpAddGoodsLike()
    }
  },

  // 将商品添加收藏
  httpAddGoodsLike() {
    return goodsModel.addGoodsLike({
      good_id: this.data.goodsId
    }).then((res) => {
      this.setData({
        isLike: true
      })
    })
  },

  // 将商品移除收藏
  httpCancelGoodsLike() {
    return goodsModel.cancelGoodsLike({
      good_ids: [this.data.goodsId]
    }).then((res) => {
      this.setData({
        isLike: false
      })
    })
  },
  // ========================================================================================

  // ========================================================================================
  // 看视频广告

  // 创建视频广告
  createVideoAd() {
    // 在页面onLoad回调事件中创建激励视频广告实例
    if (wx.createRewardedVideoAd && !this.videoAd) {
      this.videoAd = wx.createRewardedVideoAd({
        adUnitId: AD_UNIT_ID
      })
      this.videoAd.onLoad(() => {
        console.log('激励视屏加载成功');
      })
      this.videoAd.onError((err) => {
        console.log(err);
      })
      this.videoAd.onClose((status) => {
        if (status && status.isEnded || status === undefined) {
          homeModel.seckillViewAd({
            spu_id: this.data.goodsId,
            ad_id: AD_UNIT_ID
          }).then(() => {
            this.httpGetSeckillStepsInfo()
          })
        } else {
          utils.msg('请浏览完整个视频！')
          this.httpGetSeckillStepsInfo()
        }
      })
    }
  },

  // 看广告
  onViewAd() {
    const { viewAdNum, seckillTaskConfig } = this.data
    if (viewAdNum < seckillTaskConfig.viewAdNum && this.videoAd) {
      this.videoAd.load().then(() => {
        this.videoAd.show().catch((err) => {
          console.log('广告显示失败：',err);
        });
      }).catch(err => {
        utils.msg('加载失败，请稍后重试')
      });
    }
  },

  onUnload(){
    console.log('退出页面');
    this.videoAd = null;
  },

  // 观看广告获取幸运豆
  httpViewAdGetBean(adType, adComplete, adNeedType) {
    const { goodsInfo } = this.data
    return homeModel.viewAdGetBean({
      ad_id: AD_UNIT_ID, // 广告位id
      ad_type: adType, // 广告类型 1视频 2图片
      complete: adComplete, // 1完成观看 2未完成观看
      need_type: adNeedType // 1豆子 2 抽奖次数 3秒杀豆
    }).then(res => {
      let seckillBeanBlance = res.pea_blance
      let calculateDiff = seckillBeanBlance - goodsInfo.joinSeckillNeedBean
      this.setData({
        mySeckillBean: seckillBeanBlance,
        diffSeckillBean: calculateDiff >= 0 ? 0 : Math.abs(calculateDiff),
        isShowTaskPopup: false
      })
      this.httpGetMySeckillBean();
      utils.msg(`已领取${res.pea_add}精选豆`)
    })
  },
  // ========================================================================================


  // 获取秒杀豆以及观看次数
  httpGetMySeckillBean () {
    return homeModel.seckillBeanViewAdNum().then((res) => {
      this.setData({
        viewAdNum: res.ad_count,
        mySeckillBean: res.miao_blance
      })
    })
  },

  // 获取巷友商品详情
  httpGetYddGoodsDetails() {
    const { goodsId, storeId, mySeckillBean } = this.data;
    return goodsModel.getYddGoodsDetails({
      goods_id: goodsId,
      store_id: storeId
    }, {
      isNeedResponseTime: true
    }).then((res) => {
      wx.stopPullDownRefresh();
      wx.setNavigationBarTitle({
        title: res.goods_title
      });
      let storeInfoDataMap = storeInfoMap(res.store_info);
      let goodsInfoDataMap = storeGoodsDetailsMap(res);
      let nowTimestamp = res.tm
      let startTimestamp = (goodsInfoDataMap.seckillStartTime - nowTimestamp) * 1000
      let endTimestamp = (goodsInfoDataMap.seckillEndTime - nowTimestamp) * 1000
      let calculateDiff = mySeckillBean - goodsInfoDataMap.joinSeckillNeedBean
      let setDataObj = {
        storeId: res.store_info.store_id, // 店铺ID
        storeInfo: storeInfoDataMap, // 店铺信息
        seckillStatus: res.seckill_state, // 秒杀状态：1 热抢中， 2，开抢中 or 已结束 ，3未开抢
        startTimestamp: startTimestamp, // 秒杀开始时间
        endTimestamp: endTimestamp, // 秒杀结束时间
        diffSeckillBean: calculateDiff >= 0 ? 0 : Math.abs(calculateDiff), // 参加秒杀商品，相差秒杀豆
        goodsInfo: goodsInfoDataMap, // 商品信息
        goodsSwiper: res.goods_gallery_urls, // 商品轮播图
        goodsDetailsImgs: res.goods_detail, // 商品详情
        isLike: goodsInfoDataMap.isLike // 商品是否收藏
      }
      this.setData(setDataObj)
      this.initSeckill()
      this.createShareGoodsPoster()
    });
  },

  createShareGoodsPoster() {
    let self = this
    const { goodsInfo, goodsSwiper, goodsId, storeId } = this.data
    let nickName = app.globalData.userInfo && app.globalData.userInfo.nickname ? app.globalData.userInfo.nickname : ''
    let nickNameText = nickName ? `${nickName}@您，` : ''
    self.shareOption['title'] = `0元购：原价${utils.formatMoney(goodsInfo.goodsPrice)}元，现价0元，快去抢购！`;
    // self.shareOption['title'] = `${nickNameText}${goodsInfo.goodsName}正在参与秒杀，立即参加`;
    self.shareOption['path'] = `/pages/goods/seckillGoodsDetails/seckillGoodsDetails?id=${goodsId}&storeId=${storeId}`;
    self.shareOption['imageUrl'] = goodsSwiper[0];
    utils.request({
      url:'/yddgoods/SeckillGoodsPosterV2',
      data:{
        "spu_id":goodsId,
        'urlname':goodsInfo.goodsName
      },
      loading:2,
      handle:true,
      callback:function (result) {
        self.shareOption['imageUrl'] = result['res']['img_url'];
        self.shareOption['path'] = `/pages/goods/seckillGoodsDetails/seckillGoodsDetails?id=${goodsId}&storeId=${storeId}&ekey=` + result['res']['ekey'];
      }
    });
  },

  // 初始化秒杀
  initSeckill () {
    const { seckillStatus, startTimestamp, endTimestamp } = this.data
    switch (seckillStatus) {
      case 1: // 热抢中
        this.setData({
          countTime: endTimestamp,
          seckillStatus: 1
        })
        break;
      case 2: // 已结束
        this.setData({
          countTime: 1,
          seckillStatus: 2
        })
        break;
      case 3: // 未开抢
        this.setData({
          countTime: startTimestamp,
          seckillStatus: 3
        })
        break;
      default:
        break;
    }
  },

  // 获取秒杀步骤信息
  httpGetSeckillStepsInfo () {
    const { seckillSteps } = this.data
    return homeModel.getSeckillStepsInfo({
      spu_id: this.data.goodsId
    }).then(res => {
      let seckillRecord = this.group(res.spike_pre_record, 'record_type')
      seckillSteps[1].text = `2.邀请${res.new_numbers}位好友`
      this.setData({
        seckillSteps: seckillSteps,
        seckillStepsActive: res.status,
        inviteNum: res.new_numbers,
        seckillProgress: seckillRecord,
        isNoPurchase: res.is_purchase // true: 没有购买， false: 已购买过
      })
    })
  },

  group (list, fn) {
    let key, result = {}
    list.forEach(t => {
      key = typeof fn === 'function' ? fn(t) : t[fn]
      result[key] ? result[key].push(t) : (result[key] = [t])
    })
    return result
  },

  // 页面相关事件处理函数--监听用户下拉动作
  async onPullDownRefresh() {
    await this.httpGetMySeckillBean();
    await this.httpGetSeckillStepsInfo();
    wx.stopPullDownRefresh();
  },

  // 监听页面滚动
  onPageScroll() {
    this.onCloseTabbarMore()
  },

  // 生命周期函数--监听页面显示
  onShow: function () {
  },
  closePreview:function(){
    this.setData({
      isShowPreViewImage:false,
    });
  },
  saveImage:function () {
    let self = this;
    let callback;
    if(self.data.previewImage === ''){
      utils.msg('请先获取分享图片');
      return false;
    }
    callback = function(){
      wx.getImageInfo({
        src:self.data.previewImage,
        success(res) {
          console.log(res);
          wx.saveImageToPhotosAlbum({
            filePath:res.path,
            success(res) {
              utils.msg('分享图片保存成功！');
            },
            fail(res) {
              utils.msg('分享图片保存失败，请稍候再试！');
            }
          });
        },
        fail(res) {
          utils.msg('分享图片拉取失败，请稍候再试！');
        }
      });
    };
    wx.getSetting({
      success(res) {
        if (!res.authSetting['scope.writePhotosAlbum']) {
          wx.authorize({
            scope: 'scope.writePhotosAlbum',
            success () {
              callback();
            },
            fail() {
              utils.msg('您拒绝了保存权限，无法下载到相册');
            }
          })
        }else{
          callback();
        }
      },
      fail(res) {
        utils.msg('获取权限设置失败，请稍候再试！');
      }
    });
  }
});
